package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadLocal.ApUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieImpl implements ApBehaviorServcie {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 查询文章行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1.参数效验
        if (dto.getArticleId()==null || dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"数据不完整,不可以操作");
        }
        //2.判断是否是游客身份或者登录用户
        ApUser apUser = ApUserThreadLocalUtil.getApUser();
        if (apUser==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = apUser.getId();
        if (userId==0){
            //2.1如果是游客,则不可以执行以下操作
            return  ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //3.如果是登录用户的话,则展示是否关注过作者,是否点赞过,是否不喜欢,是否收藏过
           //是否关注过
        String followKey = "USER_FOLLOW_" + userId;
        Boolean followFlag = redisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());
        //是否点赞过
        String likeKey = "USER_LIKE_" + dto.getArticleId();
        Boolean likeFlag = redisTemplate.opsForHash().hasKey(likeKey, userId.toString());

        //是否不喜欢
        String unlikeKey = "USER_UNLIKE_" + dto.getArticleId();
        Boolean unlikeFlag = redisTemplate.opsForHash().hasKey(unlikeKey, userId.toString());

        //是否收藏
        String collectionKey = "USER_COLLECTION_" + dto.getArticleId();
        Boolean collectionFlag = redisTemplate.opsForHash().hasKey(collectionKey, userId.toString());


        //5.封装数据返回
        Map map = new HashMap();
        map.put("islike",likeFlag);
        map.put("isunlike",unlikeFlag);
        map.put("iscollection",collectionFlag);
        map.put("isfollow",followFlag);
        return ResponseResult.okResult(map);
    }
    }